<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Address;
use think\facade\Db;

/**
 * @extends Service<AddressService>
 */
class AddressService extends Service
{

    public function list($page, $limit, $searchQuery = null)
    {
        $w = [];
        $w[] = ['is_delete', '=', 0];
        if (!empty($searchQuery['member_id']) && $searchQuery['member_id'] != '') {
            $w[] = ['member_id', '=', $searchQuery['member_id']];
        }
        $data = Address::where($w)->page($page, $limit)->order('is_default desc,address_id desc');
        $list = $data->select()->toArray();
        return [
            'total' => $data->count(),
            'list' => $list,
        ];
    }

    public function info($id, $member_id, $is_default)
    {
        $where = [];
        if (!empty($id) && $id != '') {
            $where[] = ['address_id', '=', $id];
        }
        if (!empty($is_default) && $is_default != '') {
            $where[] = ['is_default', '=', $is_default];
        }
        $where[] = ['member_id', '=', $member_id];
        $info = Address::where($where)->find();
        if (!$info) {
            return [];
        }

        return $info->toArray();
    }

    public function del($id)
    {
        $info = Address::where('address_id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->save(['is_delete' => 1]);
    }

    public function save($data, $address_id = null)
    {
        Db::startTrans();
        if ($data['is_default'] == 1) {
            Address::where(['is_default' => 1, 'member_id' => $data['member_id']])->save(['is_default' => 0]);
        }
        try {
            $map = [
                'member_id' => $data['member_id'],
                'name' => $data['name'] ?: '',
                'mobile' => $data['mobile'] ?: '',
                'address' => $data['address'] ?: '',
                'detail_address' => $data['detail_address'] ?: '',
                'postcode' => '',
                'is_default' => $data['is_default'] ?: 0
            ];
            if (empty($address_id)) {
                Address::create($map);
            } else {
                $info = Address::where('address_id', $address_id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save($map);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }
}